import logging
from django.http import HttpResponse


from user.models import User
from . import constants
from utils.res_code import Code, error_map,json_response
from django.views import View
from utils.yuntongxun.sms import CCP
import random
from django_redis import get_redis_connection
from .forms import CheckImageForm
from utils.captcha.captcha import captcha


# 日志器
logger = logging.getLogger('django')


def image_code_view(request):
    """
    生成图片验证码
    url:/image_code/
    :param request:
    :return:
    """
    text, image = captcha.generate_captcha()
    request.session['image_code'] = text
    # 将验证码存入session中
    request.session.set_expiry(constants.IMAGE_CODE_EXPIRES)
    logger.info('Image code:{}'.format(text))

    return HttpResponse(content=image, content_type='image/jpg')


def check_username_view(request, username):
    """
    校验用户名是否存在
    url:/username/(?P<username>\w{5,20})/
    :param request:
    :param username:
    :return:
    """
    data = {
        'username': username,
        'count': User.objects.filter(username=username).count()
    }

    return json_response(data=data)


def check_mobile_view(request, mobile):
    """
    校验手机号是否存在
    url:/mobile/(?P<mobile>1[3-9]\d{9})/
    :param request:
    :param mobile:
    :return:
    """
    data = {
        'mobile': mobile,
        'count': User.objects.filter(mobile=mobile).count()
    }

    return json_response(data=data)


# class SmsCodeView(View):
#     """
#     发送短信验证码
#     url:/sms_code/
#     """
#     def post(self,request):
#         """
#         生成短信验证码
#         发送短信
#         保存这个短信验证码（保存在哪？）
#         保存发送记录
#         """
#         form = CheckImageForm(request.POST)
#         if form.is_valid():
#             # 获取手机号码
#             mobile = form.cleaned_data.get('mobile')
#             # 生成短信验证码
#             sms_code = ''.join([random.choice('0123456789') for _ in range(constants.SMS_CODE_LENGTH)])
#             # 发送短信验证码，调用接口
#             logger.info('发送短信验证码[正常][mobile:%s sms_code:%s]'%(mobile,sms_code))
#             # 保存这个验证码 时限 session Redis
#             sms_flag_key = 'sms_flag_{}'.format(mobile)
#
#             sms_text_key = 'sms_text_{}'.format(mobile)
#             redis_conn = get_redis_connection(alias='verify_code')
#             pl = redis_conn.pipeline()
#             try:
#                 pl.setex(sms_flag_key,constants.SMS_CODE_INTERVAL,constants.SMS_CODE_TEMP_ID)
#                 pl.setex(sms_text_key,constants.IMAGE_CODE_EXPIRES*60,sms_code)
#                 pl.execute()
#                 return json_response(errmsg='短信验证码发送成功！')
#             except Exception as e:
#                 logger.error('redis 执行异常：{}'.format(e))
#
#                 return json_response(errno=Code.UNKOWNERR, errmsg=error_map[Code.UNKOWNERR])
#         else:
#             # 将表单的报错信息进行拼接
#             err_msg_list = []
#             for item in form.errors.get_json_data().values():
#                 err_msg_list.append(item[0].get('message'))
#                 # print(item[0].get('message'))   # for test
#             err_msg_str = '/'.join(err_msg_list)  # 拼接错误信息为一个字符串
#
#             return json_response(errno=Code.PARAMERR, errmsg=err_msg_str)
class SmsCodeView(View):
    """
    发送短信验证码
    POST /sms_code/
    """
    def post(self, request):
        # 1.校验参数：校验手机号码

        form = CheckImageForm(request.POST, request=request)
        if form.is_valid():
            # 2.获取手机
            mobile = form.cleaned_data.get('mobile')
            # 3.生成手机验证码
            sms_code = ''.join([random.choice('0123456789') for _ in range(constants.SMS_CODE_LENGTH)])
            # 4.发送手机验证码
            ccp = CCP()
            try:
                res = ccp.send_template_sms(mobile, [sms_code, constants.SMS_CODE_EXPIRES], "1")
                if res == 0:
                    logger.info('发送短信验证码[正常][mobile: %s sms_code: %s]' % (mobile, sms_code))
                else:
                    logger.error('发送短信验证码[失败][moblie: %s sms_code: %s]' % (mobile, sms_code))
                    return json_response(errno=Code.SMSFAIL, errmsg=error_map[Code.SMSFAIL])
            except Exception as e:
                logger.error('发送短信验证码[异常][mobile: %s message: %s]' % (mobile, e))
                return json_response(errno=Code.SMSERROR, errmsg=error_map[Code.SMSERROR])


            # 5.保存到redis数据库
            # 创建短信验证码发送记录
            sms_flag_key = 'sms_flag_{}'.format(mobile)
            # 创建短信验证码内容记录
            sms_text_key = 'sms_text_{}'.format(mobile)

            redis_conn = get_redis_connection(alias='verify_code')
            pl = redis_conn.pipeline()

            try:
                pl.setex(sms_flag_key, constants.SMS_CODE_INTERVAL, 1)
                pl.setex(sms_text_key, constants.SMS_CODE_EXPIRES*60, sms_code)
                # 让管道通知redis执行命令
                pl.execute()
                return json_response(errmsg="短信验证码发送成功！")
            except Exception as e:
                logger.error('redis 执行异常：{}'.format(e))

                return json_response(errno=Code.UNKOWNERR, errmsg=error_map[Code.UNKOWNERR])

        else:
            # 将表单的报错信息进行拼接
            err_msg_list = []
            for item in form.errors.get_json_data().values():
                err_msg_list.append(item[0].get('message'))
                # print(item[0].get('message'))   # for test
            err_msg_str = '/'.join(err_msg_list)  # 拼接错误信息为一个字符串

            return json_response(errno=Code.PARAMERR, errmsg=err_msg_str)